<script lang="ts" setup>
import { reactive, ref, watch, nextTick } from "vue"
import { createAgencyDataApi, getAgencyDataApi, deleteAgencyDataApi, updateAgencyDataApi } from "@/api/agency"
import { type IAgencyRequestData } from "@/api/agency/types/agency"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, CirclePlus, RefreshRight } from "@element-plus/icons-vue"

import { usePagination } from "@/hooks/usePagination"
import { checkPhoneNumber } from "@/utils/validate"
defineOptions({
  name: "Agency"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

//#region 增
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = reactive<any>({
  user_card_name: "", //**姓名 */
  user_sex: "", //**性别 */
  user_card_id: "", //**身份证号 */
  user_name: "", //**账号 */
  user_password: "", //**密码 */
  user_mobile: "", //**登录手机号 */
  user_super: "", //**上级代理 */
  user_level: "" //**分销等级 */
})
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  user_id: "",
  user_name: "",
  user_mobile: "",
  user_super: ""
})
const DlList = ref<any>([])

const formRules: FormRules = reactive({
  user_name: [{ required: true, trigger: "blur", message: "请输入账户名称" }],
  user_password: [{ required: true, trigger: "blur", message: "请输入密码" }],
  user_mobile: [{ required: true, validator: checkPhoneNumber, trigger: "blur" }],
  user_super: [{ required: true, trigger: "blur", message: "选择上级代理" }],
  user_level: [{ required: true, trigger: "blur", message: "请选择分销等级" }]
})
const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (currentUpdateId.value === undefined) {
        createAgencyDataApi(formData).then(() => {
          ElMessage.success("新增成功")
          dialogVisible.value = false
          getTableData()
        })
      } else {
        const data = ref<any>()
        data.value = formData
        data.value.user_id = currentUpdateId.value
        updateAgencyDataApi(data.value).then(() => {
          ElMessage.success("修改成功")
          dialogVisible.value = false
          getTableData()
        })
      }
    } else {
      return false
    }
  })
}

//#endregion
const resetForm = () => {
  currentUpdateId.value = undefined
  clearValidate()
}

//#region 删
const handleDelete = (row: IAgencyRequestData) => {
  ElMessageBox.confirm(`正在删除账户：${row.user_name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteAgencyDataApi(row.user_id).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const currentUpdateId = ref<undefined | string>(undefined)
const handleUpdate = (row: IAgencyRequestData) => {
  dialogVisible.value = true
  nextTick(() => {
    currentUpdateId.value = row.user_id
    formData.user_card_name = row.user_card_name
    formData.user_sex = row.user_sex
    formData.user_card_id = row.user_card_id
    formData.user_name = row.user_name
    formData.user_password = row.user_password
    formData.user_mobile = row.user_mobile
    formData.user_super = row.user_super
    formData.user_level = row.user_level
  })
}
//#endregion

//#region 查
const tableData = ref<IAgencyRequestData[]>([])

const getTableData = () => {
  loading.value = true
  getAgencyDataApi({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    ...searchData
  })
    .then((res: any) => {
      paginationData.total = res.data.total
      tableData.value = res.data.list
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const getTableData1 = () => {
  loading.value = true
  getAgencyDataApi({
    page: 1,
    size: 1000
  })
    .then((res: any) => {
      DlList.value = res.data.list
    })
    .catch(() => {
      DlList.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
getTableData1()
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const handleRefresh = () => {
  getTableData()
}
//#endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
// ** 清除规则报错信息
const clearValidate = () => {
  formRef.value?.clearValidate()
  formRef.value?.resetFields()
}
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="user_id" label="ID">
          <el-input v-model.trim="searchData.user_id" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="user_name" label="账号名">
          <el-input v-model.trim="searchData.user_name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="user_mobile" label="手机号">
          <el-input v-model.trim="searchData.user_mobile" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="user_super" label="上级代理">
          <!-- <el-input v-model.trim="searchData.user_super" placeholder="请输入" /> -->
          <el-select v-model="searchData.user_super">
            <el-option v-for="item in DlList" :value="item.user_id" :label="item.user_name" :key="item.user_id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">添加账户</el-button>
        </div>
        <div>
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="user_id" label="ID" width="120" align="center" />
          <el-table-column prop="user_name" label="账户名" align="center" />
          <el-table-column prop="user_mobile" label="手机号" align="center" />
          <el-table-column label="上级代理" align="center">
            <template #default="scope">
              <el-select v-model="scope.row.user_super" disabled>
                <el-option v-for="item in DlList" :value="item.user_id" :label="item.user_name" :key="item.user_id" />
              </el-select>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="user_level" label="分销等级" align="center" /> -->
          <el-table-column prop="" label="月销量" align="center" />
          <el-table-column prop="" label="发货成功量" align="center" />
          <el-table-column prop="" label="激活成功数量" align="center" />
          <el-table-column prop="" label="结佣金额" align="center" />
          <el-table-column prop="" label="支付情况" align="center" />
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增 修改-->
    <el-dialog
      v-model="dialogVisible"
      :title="currentUpdateId === undefined ? '新增' : '修改'"
      @close="resetForm"
      width="60%"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="user_name" label="账户名">
          <el-input v-model="formData.user_name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="user_password" label="密码">
          <el-input v-model="formData.user_password" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="user_mobile" label="登录手机号">
          <el-input v-model="formData.user_mobile" :maxlength="11" show-word-limit placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="user_super" label="上级代理">
          <!-- <el-input v-model="formData.user_super" disabled placeholder="请输入" /> -->
          <el-select v-model="formData.user_super">
            <el-option v-for="item in DlList" :value="item.user_id" :label="item.user_name" :key="item.user_id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="user_level">
          <template #label>
            <span>分销等级</span>
            <el-tooltip class="box-item" effect="customized" placement="bottom">
              <template #content>
                月激活50张以内,【会员】,每张利润50-80元<br />
                月激活50张以上,【初级代理】,每张利润80-100元<br />
                月激活200张以上,【中级代理】,每张利润100-130<br />
                月激活500张以上,【高级代理】,每张利润130-160<br />
                月激活1000单以上,【核心代理】,每张利润160以上<br />
              </template>
              <el-icon style="cursor: pointer"><InfoFilled /></el-icon>
            </el-tooltip>
          </template>
          <el-select v-model="formData.user_level" clearable placeholder="请选择" style="width: 240px">
            <el-option label="会员" value="会员" />
            <el-option label="初级代理" value="初级代理" />
            <el-option label="中级代理" value="中级代理" />
            <el-option label="高级代理" value="高级代理" />
            <el-option label="核心代理" value="核心代理" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.block {
  padding: 30px 0;
  text-align: center;
  box-sizing: border-box;
  vertical-align: top;
}
</style>
<style>
.el-popper.is-customized {
  /* Set padding to ensure the height is 32px */
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
  background: linear-gradient(45deg, #b2e68d, #bce689);
  right: 0;
}
</style>
